package com.ulk.systempermission.utils;

import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.RecoverySystem;
import android.util.Log;

import java.io.File;
import java.io.IOException;

/**
 * Created by su on 2016/6/6.
 */
public class RebootUtils {
    private final static String TAG = "Upgrade.RebootUtils";

    public static void rebootInstallPackage(final Context context, final File packageFile) {
        Log.w(TAG, "!!! REBOOT INSTALL PACKAGE !!!");

        Log.d(TAG, "file path is " + packageFile.getPath());
        // The reboot call is blocking, so we need to do it on another thread.
        Thread thr = new Thread("Reboot") {
            @Override
            public void run() {
                try {
                    RecoverySystem.installPackage(context, packageFile);
                } catch (IOException e) {
                    Log.e(TAG, "Can't perform rebootInstallPackage", e);
                }
            }
        };
        thr.start();
    }

    public static void rebootRecovery(Context context) {
        Log.w(TAG, "!!! REBOOT RECOVERY !!!");
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        pm.reboot("recovery");
    }

    public static void rebootNormal(Context context) {
        Log.w(TAG, "!!! REBOOT NORMAL !!!");
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        pm.reboot("normal_reboot");
    }

    public static void rebootWipeUserData(final Context context) {
        Log.w(TAG, "!!! REBOOT WIPE USER DATA !!!");
        // The reboot call is blocking, so we need to do it on another thread.
        Thread thr = new Thread("Reboot") {
            @Override
            public void run() {
                try {
                    RecoverySystem.rebootWipeUserData(context);
                } catch (IOException e) {
                    Log.e(TAG, "Can't perform rebootInstallPackage", e);
                }
            }
        };
        thr.start();
    }

    public static void rebootWipeCache(final Context context) {
        Log.w(TAG, "!!! REBOOT WIPE USER DATA !!!");
        // The reboot call is blocking, so we need to do it on another thread.
        Thread thr = new Thread("Reboot") {
            @Override
            public void run() {
                try {
                    RecoverySystem.rebootWipeCache(context);
                } catch (IOException e) {
                    Log.e(TAG, "Can't perform rebootInstallPackage", e);
                }
            }
        };
        thr.start();
    }

    public static void rebootRestoreFactorySettings(final Context context) {
        if (null != context) {
            context.sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR"));
        }
    }
}
